package com.sanjin.controller;

import com.sanjin.exception.MyException;
import com.sanjin.utils.ResponseVoUtils;
import com.sanjin.vo.ResponseVo;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * @description:
 * @author: sanjin
 * @date: 2019/4/7 10:09
 */
@ControllerAdvice
@RestController
public class GlobalExceptionController {


    /**
     * 全局 MyException 异常处理
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(MyException.class)
    public ResponseVo defaultExceptionHandler(HttpServletRequest req, MyException e){
        return ResponseVoUtils.error(e.getMessage());
    }

    /**
     * 捕获表单验证 MethodArgumentNotValidException 异常
     * @param e
     * @return
     * @throws Exception
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseVo methodArgumentValidExceptionHandler(MethodArgumentNotValidException e) throws Exception {
        String message = "";
        //如果抛出了异常，这个getErrorCount一定会>0
        if (e.getBindingResult().getErrorCount() > 0) {
            //校验会把所有不通过的选项的错误信息记录下来，现在先默认给前端提供第一个错误信息
            message = e.getBindingResult().getAllErrors().get(0).getDefaultMessage();
        }
        return ResponseVoUtils.error(message);
    }
}
